package cn.liyiming.bbs.modular.system.controller;

import cn.liyiming.bbs.modular.system.model.*;
import cn.liyiming.bbs.modular.system.service.impl.*;
import cn.liyiming.bbs.util.AjaxResponse;
import cn.liyiming.bbs.util.CommonUtil;
import cn.liyiming.bbs.util.RedisKeyUtils;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @program: bbs
 * @description: 提问区
 * @author: 李一鸣
 * @create: 2020-02-29 18:36
 **/
@RequestMapping("/article")
@Controller
public class ArticleController extends BaseController {

    /**
     * 上传文件本地路径
     */
    @Value("${upload.path}")
    private String path;
    /**
     * 上传文件相对路径
     */
    @Value("${upload.relativePath}")
    private String relativePath;

    @Autowired
    private ArticleTypeServiceImpl articleTypeService;

    @Autowired
    private ArticleServiceImpl articleService;

    @Autowired
    private CommentServiceImpl commentService;

    @Autowired
    private RedisServiceImpl redisService;

    @Autowired
    private LikeServiceImpl likeService;


    @RequestMapping("/list/{artUserId}")
    @ResponseBody
    public Object ArticleList(@PathVariable("artUserId") Integer artUserId, @RequestParam(defaultValue = "1")Integer limit, @RequestParam(defaultValue = "10")Integer page) {
        return articleService.selectByArticleUserId(artUserId, limit, page);
    }


/**
* @Description: 通过session获取userId但是感觉每次都要取，麻烦
* @Param: [article, session]
* @return: java.lang.Object
* @Author: 李一鸣
* @Date: 2020/3/20
*/
    @RequestMapping({"/addArticle"})
    @ResponseBody
    public Object add(Article article, HttpSession session) {
        article.setCreateTime(new Date());
        article.setStatus(1);
        User user = (User) session.getAttribute("user");
        article.setArtUserId(user.getId());
        articleService.insert(article);
        return AjaxResponse.success();
    }


    @RequestMapping({"/likeArticle/{ArticleId}/{likeUserId}"})
    @ResponseBody
    public Object Like(@PathVariable("ArticleId") Integer ArticleId, @PathVariable("likeUserId")Integer likeUserId) {
        //先把数据存到Redis里,再定时存回数据库
        Like like = likeService.getByArticleIdAndLikeUserId(ArticleId, likeUserId);
        if (like == null) {
            //之前没有点过赞
            redisService.saveLiked2Redis(ArticleId,likeUserId);
            redisService.incrementLikedCount(ArticleId);
            List<Like> likedDataFromRedis = redisService.getLikedDataFromRedis();
            System.out.println("redis数据：————————————————————————————————————》"+likedDataFromRedis);
            likeService.transLikedFromRedis2DB();

            List<LikedCountDTO> likedCountFromRedis = redisService.getLikedCountFromRedis();
            likeService.transLikedCountFromRedis2DB();
            System.out.println("redis计数：————————————————————————————————————》"+likedCountFromRedis);

            return ResponseData.success();
        } else {
            return ResponseData.error("您已经点过赞");
        }

    }

    @RequestMapping({"/unlikeArticle"})
    @ResponseBody
    public Object unlike(Integer ArticleId, Integer likeUserId) {
        //先把数据存到Redis里,再定时存回数据库
        redisService.unlikeFromRedis(ArticleId,likeUserId);
        redisService.decrementLikedCount(ArticleId);
        return AjaxResponse.success();
    }

    @RequestMapping({"/index"})
    public String index(Model model) {

        return "pages/jie/index";
    }

    @RequestMapping({"/detail/{articleId}"})
    public String detail(Model model,@PathVariable("articleId") Integer articleId) {
        Article article = articleService.selectById(articleId);
        List<Comment> comments = commentService.selectAllCommentByArtId(articleId);
        model.addAttribute("article",article);
        model.addAttribute("comments",comments);
        return "pages/jie/detail";
    }

    @RequestMapping({"/add"})
    public String add(Model model) {

        List<ArticleType> articleTypes = articleTypeService.selectAllType();
        model.addAttribute("articleTypes", articleTypes);
        return "pages/jie/add";
    }

    /**
     * @Description:  多文件上传
     * @Param: [file]
     * @return: java.lang.Object
     * @Author: 李一鸣
     * @Date: 2020/1/13
     */
    @RequestMapping("/fileUpload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file) {

        String originalFilename = file.getOriginalFilename();
        String src = CommonUtil.uploadFile(file,path,relativePath,originalFilename);
        HashMap map = new HashMap(16);
        map.put("src",relativePath+src);
        map.put("title",src);
        return new SuccessResponseData(0,"上传文件成功",map);
    }
}
